package my.jwds.p211;

import java.util.*;

public class WordDictionary {

    public static void main(String[] args) {
        WordDictionary obj = new WordDictionary();
        obj.addWord("wocao");
        obj.addWord("nihao");
        System.out.println(obj.search("nihao"));
    }

    Set<String> cache ;
    Map<Integer, List<String>> countAsStr ;



    public WordDictionary() {
        cache = new HashSet<>();
        countAsStr = new HashMap<>();
    }

    public void addWord(String word) {
        if (!cache.contains(word)){
            cache.add(word);
            List<String> countStr = countAsStr.get(word.length());
            if (countStr == null){
                countStr = new ArrayList<>();
                countAsStr.put(word.length(),countStr);
            }
            countStr.add(word);
        }

    }

    public boolean search(String word) {
        boolean search = cache.contains(word);
        if (!search && word.indexOf(".") != -1){
            List<String> countStr = countAsStr.get(word.length());
            if (countStr != null){
                for (String compare : countStr) {
                    if (equalsStr(compare,word)){
                        search = true;
                        break;
                    }
                }
            }
        }
        return search;
    }
    
    protected boolean equalsStr(String str,String search){
        int length = str.length();
        for (int i = 0; i < length; i++) {
            if (str.charAt(i) != search.charAt(i) && search.charAt(i) != '.')return false;
        }
        return true;
    }
}
